package com.seven.leetcode.utils;

public class TreeNode {

    public int val;

    public TreeNode left;

    public TreeNode right;

    public TreeNode() {
    }

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public static TreeNode fromArray(Integer[] nums) {
        if (null == nums || nums.length == 0) {
            return null;
        }

        TreeNode node = new TreeNode(nums[0]);
        getChildren(node, 0, nums);

        return node;
    }

    private static void getChildren(TreeNode root, int index, Integer[] nums) {
        if (null == root) {
            return;
        }

        int idx = index * 2 + 1;
        if (idx < nums.length) {
            Integer num = nums[idx];
            if (null != num) {
                root.left = new TreeNode(nums[idx]);
                getChildren(root.left, idx, nums);
            }
        }
        idx++;
        if (idx < nums.length) {
            Integer num = nums[idx];
            if (null != num) {
                root.right = new TreeNode(nums[idx]);
                getChildren(root.right, idx, nums);
            }
        }
    }

    @Override
    public String toString() {
        return "TreeNode{" +
            "val=" + val +
            ", left=" + left +
            ", right=" + right +
            '}';
    }
}
